<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="bg-white border-b border-gray-200 sticky top-0 z-50">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between h-16">
          <div class="flex items-center gap-3">
            <div class="w-10 h-10 bg-blue-500 rounded-lg flex items-center justify-center">
              <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/></svg>
            </div>
            <span class="text-xl font-semibold text-gray-900">校园快递代拿</span>
            <span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded">下单者</span>
          </div>
          <HeaderActions />
        </div>
      </div>
    </header>

    <!-- 面包屑 -->
    <div class="bg-white border-b border-gray-200">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-2 text-sm text-gray-500">
        <button class="hover:text-blue-600" @click="$router.push('/order/my')">我的订单</button>
        <span class="mx-2">/</span>
        <span class="text-gray-900">订单详情</span>
      </div>
    </div>

    <!-- 内容 -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- 左：订单信息 -->
        <section class="lg:col-span-2 bg-white rounded-lg shadow-sm p-6">
          <div class="flex items-start justify-between mb-6">
            <div>
              <h1 class="text-2xl font-bold text-gray-900 mb-1">{{ detail.title }}</h1>
              <div class="flex items-center gap-3 text-sm text-gray-500">
                <span>订单编号：{{ orderId }}</span>
                <span>创建时间：{{ detail.time }}</span>
                <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium" :class="statusPill(detail.status)">{{ statusLabel(detail.status) }}</span>
              </div>
            </div>
            <div class="text-right">
              <div class="text-gray-500 text-sm">订单金额</div>
              <div class="text-2xl font-bold text-gray-900">¥{{ detail.amount }}</div>
            </div>
          </div>

          <div class="space-y-8">
            <div>
              <h2 class="text-lg font-semibold text-gray-900 mb-4">物品信息</h2>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                <div><span class="text-gray-500">物品类型：</span><span class="text-gray-900">{{ detail.itemType || '快递包裹' }}</span></div>
                <div><span class="text-gray-500">物品数量：</span><span class="text-gray-900">{{ detail.itemCount || '1件' }}</span></div>
                <div class="md:col-span-2"><span class="text-gray-500">物品描述：</span><span class="text-gray-900">{{ detail.itemDesc || detail.desc || '—' }}</span></div>
              </div>
            </div>

            <div>
              <h2 class="text-lg font-semibold text-gray-900 mb-4">取件信息</h2>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                <div><span class="text-gray-500">取件地点：</span><span class="text-gray-900">{{ detail.pickupLocation || '—' }}</span></div>
                <div><span class="text-gray-500">取件时间/单号：</span><span class="text-gray-900">{{ detail.pickupRef || '—' }}</span></div>
                <div><span class="text-gray-500">期望时间：</span><span class="text-gray-900">{{ detail.pickupTime || '—' }}</span></div>
              </div>
              <div class="mt-3">
                <button
                  type="button"
                  class="inline-flex items-center px-3 py-1.5 text-xs font-medium rounded border border-blue-500 text-blue-600 hover:bg-blue-50"
                  @click="openPickupMap"
                >
                  查看取件点地图（高德）
                </button>
              </div>
            </div>

            <div>
              <h2 class="text-lg font-semibold text-gray-900 mb-4">送达信息</h2>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                <div><span class="text-gray-500">送达地点：</span><span class="text-gray-900">{{ detail.dropoffLocation || '—' }}</span></div>
                <div class="md:col-span-2"><span class="text-gray-500">详细地址：</span><span class="text-gray-900">{{ detail.dropoffDetail || '—' }}</span></div>
              </div>
              <div class="mt-3">
                <button
                  type="button"
                  class="inline-flex items-center px-3 py-1.5 text-xs font-medium rounded border border-blue-500 text-blue-600 hover:bg-blue-50"
                  @click="openDropoffMap"
                >
                  查看送达点地图（高德）
                </button>
              </div>
            </div>

            <div>
              <h2 class="text-lg font-semibold text-gray-900 mb-4">备注信息</h2>
              <p class="text-sm text-gray-700">{{ detail.remark || '无' }}</p>
            </div>
          </div>
        </section>

        <!-- 右：状态流与操作（订单已取消时不展示进度） -->
        <aside v-if="detail.status !== 'cancelled'" class="bg-white rounded-lg shadow-sm p-6 h-fit">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">订单进度</h3>
          <ol class="relative border-l-2 border-gray-300 ml-4 text-sm">
            <li class="mb-6 ml-4" v-for="(step, idx) in steps" :key="idx">
              <div class="absolute w-3 h-3 rounded-full -left-1.5 border" :class="idx <= currentStep ? 'bg-blue-600 border-blue-600' : 'bg-white border-gray-300'"></div>
              <time class="text-gray-400">{{ step.time }}</time>
              <div class="text-gray-900 font-medium">{{ step.title }}</div>
              <div class="text-gray-500">{{ step.desc }}</div>
            </li>
          </ol>
          <div class="mt-6 flex gap-3">
            <button class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700" @click="$router.push('/order/my')">返回列表</button>
            <button v-if="canContact" class="px-4 py-2 border border-blue-600 text-blue-600 rounded hover:bg-blue-50" @click="contactCourier">联系接手</button>
            <button v-if="detail.status === 'delivered'" class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700" @click="markCompleted">确认已完成</button>
          </div>
        </aside>
      </div>
    </main>
  </div>
</template>

<script>
import axios from 'axios'
import HeaderActions from '../components/HeaderActions.vue'
export default {
  name: 'OrderDetail',
  components: { HeaderActions },
  data() {
    return {
      orderId: this.$route.params.id,
      detail: {},
      steps: [],
      currentStep: 0,
      raw: null,
      canContact: false
    }
  },
  methods: {
    openPickupMap() {
      const loc = (this.detail && this.detail.pickupLocation) || ''
      if (!loc) {
        alert('暂无取件地点信息')
        return
      }
      const keyword = `云浮市 广东药科大学 都杨镇文华路368号 ${loc}`
      const url = `https://www.amap.com/search?query=${encodeURIComponent(keyword)}`
      const win = window.open(url, '_blank')
      if (!win) {
        // 如果浏览器拦截了新标签页，则退化为当前页跳转
        window.location.href = url
      }
    },
    openDropoffMap() {
      const loc = (this.detail && (this.detail.dropoffDetail || this.detail.dropoffLocation)) || ''
      if (!loc) {
        alert('暂无送达地点信息')
        return
      }
      const keyword = `云浮市 广东药科大学 都杨镇文华路368号 ${loc}`
      const url = `https://www.amap.com/search?query=${encodeURIComponent(keyword)}`
      const win = window.open(url, '_blank')
      if (!win) {
        window.location.href = url
      }
    },
    statusLabel(s) {
      const statusMap = {
        'pending': '待接单',
        'ongoing': '配送中',
        'picked': '已取件',
        'delivered': '已送达',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[s] || '待处理'
    },
    statusPill(s) {
      const classMap = {
        'pending': 'bg-gray-100 text-gray-600',
        'ongoing': 'bg-yellow-100 text-yellow-700',
        'picked': 'bg-amber-100 text-amber-700',
        'delivered': 'bg-blue-100 text-blue-700',
        'completed': 'bg-green-100 text-green-700',
        'cancelled': 'bg-red-100 text-red-700'
      }
      return classMap[s] || 'bg-gray-100 text-gray-600'
    },
    async contactCourier() {
      if (!this.canContact) return
      const userId = Number(localStorage.getItem('userId'))
      if (!userId) { this.$router.push('/login'); return }
      try {
        const ordererId = Number(this.raw && (this.raw.orderer_user_id || this.raw.order_user_id || this.raw.order_user)) || 0
        // 后端已返回 courier 对应的 users.id 为 courier_user，优先使用它
        const courierId = Number(this.raw && (this.raw.courier_user || this.raw.courier_user_id || this.raw.courier_user_id)) || 0
        if (!courierId) { alert('暂无接手人，无法发起对话'); return }
        const { data } = await axios.post('/api/messages/conversations', {
          participants: [userId, courierId],
          order_id: Number(this.orderId),
          type: 1
        })
        const cid = data && data.data && data.data.id
        this.$router.push({ path: '/messages', query: { cid } })
      } catch (e) {
        console.error('发起会话失败', e)
        alert('发起会话失败，请稍后再试')
      }
    },
    async markCompleted() {
      if (!confirm('确认订单已完成？完成后将无法再修改。')) return
      try {
        await axios.put(`/api/orders/${this.orderId}`, { status: 3 })
        // 刷新订单详情
        const { data } = await axios.get(`/api/orders/${this.orderId}`)
        if (data && data.success !== false) {
          const d = data.data || {}
          this.detail.status = 'completed'
          this.currentStep = 4
          const fmt = (v) => v ? String(v).replace('T',' ').slice(0,19) : ''
          const updated = fmt(d.updated_at)
          this.steps[4] = { title: '已完成', desc: '订单已送达并确认完成', time: updated || '—' }
        }
        alert('订单已标记为已完成')
      } catch (e) {
        console.error('标记完成失败', e)
        alert('标记完成失败，请稍后再试')
      }
    }
  },
  async mounted() {
    try {
      const { data } = await axios.get(`/api/orders/${this.orderId}`)
      if (data && data.success !== false) {
        const d = data.data || {}
        this.raw = d
        // 状态映射（与后端保持一致）：1=待接单, 2=配送中, 3=已取件, 4=已送达, 5=已完成, 6=已取消
        const statusMap = (s) => {
          const v = Number(s)
          if (v === 1) return 'pending'
          else if (v === 2) return 'ongoing'
          else if (v === 3) return 'picked'
          else if (v === 4) return 'delivered'
          else if (v === 5) return 'completed'
          else if (v === 6) return 'cancelled'
          return 'pending'
        }
        const amount = (d.final_fee ?? d.suggested_fee ?? d.amount ?? d.fee ?? 0)
        // 从 delivery_address 拆分楼栋与详细地址（格式如："9栋 9-307"）
        let dropLoc = d.delivery_address || ''
        let dropDetail = ''
        if (dropLoc.includes(' ')) {
          const i = dropLoc.indexOf(' ')
          dropDetail = dropLoc.slice(i + 1)
          dropLoc = dropLoc.slice(0, i)
        }
        const fmt = (v) => v ? String(v).replace('T',' ').slice(0,19) : ''
        this.detail = {
          title: '快递代拿订单',
          desc: d.note || `${d.pickup_location || ''} → ${d.delivery_address || ''}`.trim(),
          amount: Number(amount).toFixed(2),
          time: (d.created_at && String(d.created_at).replace('T',' ').slice(0,19)) || '',
          status: statusMap(d.status),
          itemType: d.express_type || '',
          itemCount: d.package_size || '',
          pickupLocation: d.pickup_location || '',
          pickupRef: d.pickup_code || '',
          pickupTime: fmt(d.pickup_time),
          dropoffLocation: dropLoc || '',
          dropoffDetail: dropDetail || ''
        }

        // 进度
        // 构建基于后端状态/时间的进度
        const created = fmt(d.created_at)
        const accepted = fmt(d.accepted_at)
        const pickedTime = fmt(d.picked_up_at || d.accepted_at)
        const deliveredTime = fmt(d.delivered_at || d.picked_up_at || d.accepted_at)
        const completedTime = fmt(d.completed_at || d.updated_at || d.accepted_at || d.created_at)
        const status = statusMap(d.status)

        const isCompleted = status === 'completed'
        const isCancelled = status === 'cancelled'
        const isDelivered = status === 'delivered'
        const isPicked = status === 'picked'
        const isOngoing = status === 'ongoing'

        const steps = [
          { title: '已下单', desc: '订单已创建', time: created || '—' },
          { title: accepted ? '已接单' : '待接单', desc: accepted ? '代拿员已接单' : '等待代拿员接单', time: accepted || '—' },
          { title: isPicked || isDelivered || isCompleted ? '已取件' : (isOngoing ? '配送中' : '待接单'), desc: isPicked || isDelivered || isCompleted ? '代拿员已取件' : (isOngoing ? '代拿员配送中' : '等待接单'), time: pickedTime || '—' },
          { title: isDelivered || isCompleted ? '已送达' : (isPicked ? '配送中' : (isCancelled ? '已取消' : '等待送达')), desc: isDelivered || isCompleted ? '代拿员已送达' : (isPicked ? '代拿员配送中' : (isCancelled ? '订单已取消' : '等待送达')), time: (isDelivered || isCompleted || isCancelled || isPicked) ? (deliveredTime || pickedTime || accepted || created || '—') : '—' },
          { title: isCompleted ? '已完成' : (isCancelled ? '已取消' : '待确认'), desc: isCompleted ? '订单已确认完成' : (isCancelled ? '订单已取消' : '等待确认完成'), time: (isCompleted || isCancelled) ? (completedTime || '—') : '—' }
        ]
        this.steps = steps
        
        // 根据状态确定当前步骤
        if (isCancelled) this.currentStep = 4
        else if (isCompleted) this.currentStep = 4
        else if (isDelivered) this.currentStep = 3
        else if (isPicked) this.currentStep = 2
        else if (isOngoing) this.currentStep = 2
        else if (accepted) this.currentStep = 1
        else this.currentStep = 0

        const courierId = Number(d.courier_user_id || d.courier_user || 0)
        // 只有订单进行中（配送中/已取件/已送达）时允许联系
        this.canContact = !!courierId && (status === 'ongoing' || status === 'picked' || status === 'delivered')
      }
    } catch (e) {
      console.error('获取订单详情失败', e)
    }
  }
}
</script>


